<?php

namespace Beerus\Modules\DesignerVote\Controllers;

use App\Http\Controllers\Controller;
use Biz\model\designerAward\Sign;
use Biz\model\designerAward\User;
use Doraemon\model\Member;
use Doraemon\pockets\excel\DownExcel;
use Encore\Admin\Layout\Content;
use Illuminate\Http\Request;
use App\Pockets\GridDataModel as pGridDataModel;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Biz\service\designerAward\AdmDesignerAward as sAdmDesignerAward;

class DesignerController extends Controller
{
    public function __construct()
    {
        parent::__construct();
        Admin::script('$(".pjax-container").attr("id","pjax-container");');
    }

    /**
     * 设计师报名列表
     * @param Content $content
     * @param Request $request
     * @return Content
     */
    public function index(Content $content, Request $request)
    {
        $requestParams = $request->all();
        $condition = $this->_index_condition($requestParams);
        $count = sAdmDesignerAward::admUserCount($condition);
        $tips = "<div class='alert alert-info'>共{$count}个账号报名</div>";
        $pageSize = $request->input("per_page", 10);
        $page = $request->input("page", 1);
        $limit = [
            ($page - 1) * $pageSize,
            $pageSize
        ];
        return $content->header('设计师报名列表')
            ->row($tips)
            ->row($this->_index_grid($condition, $limit));
    }

    private function _index_condition($request)
    {
        $response = [];
        $uids = [];
        $conditionBreak = false;

        //用户id
        if (isset($request['uid']) && ($request['uid'] !== '')) {
            $uids = [$request['uid']];
            $response['uid'] = empty($uids) ? '0' : $uids;
        }

        //用户身份
        if (isset($request['role']) && ($request['role'] !== '')) {
            $tempUids = User::select('uid', []);
            $tempUids = Member::select('uid', ['uid' => $tempUids, 'type' => $request['role']]);
            if (empty($tempUids)) {
                $conditionBreak = true;
                $uids = 0;
            } else {
                $uids = empty($uids) ? $tempUids : array_intersect($uids, $tempUids);
            }
            $response['uid'] = empty($uids) ? '0' : $uids;
        }

        //赛区
        if (isset($request['area']) && ($request['area'] !== '')) {
            if ($conditionBreak == false) {
                $tempUids = User::select('uid', ['area' => $request['area']]);
                if (empty($tempUids)) {
                    $conditionBreak = true;
                    $uids = 0;
                } else {
                    $uids = empty($uids) ? $tempUids : array_intersect($uids, $tempUids);
                }
            }
            $response['uid'] = empty($uids) ? '0' : $uids;
        }

        //报名通道
        if (isset($request['channel']) && ($request['channel'] > 0)) {
            if ($conditionBreak == false) {
                $tempUids = User::select('uid', ['types' => $request['channel']]);
                if (empty($tempUids)) {
                    $uids = 0;
                } else {
                    $uids = empty($uids) ? $tempUids : array_intersect($uids, $tempUids);
                }
            }
            $response['uid'] = empty($uids) ? '0' : $uids;
        }


        //户型
        if (isset($request['house']) && ($request['house'] !== '')) {
            $response['house'] = $request['house'];
        }

        //审核状态
        if (isset($request['check_status']) && ($request['check_status'] !== '')) {
            $response['check_status'] = $request['check_status'];
        }

        //勾选软装
        if (isset($request['is_soft']) && ($request['is_soft'] > 0)) {
            $response['crown_award'] = $request['is_soft'] == 1 ? 1 : 0;
        }

        //备注
        if (isset($request['is_memo']) && ($request['is_memo'] > 0)) {
            if ($request['is_memo'] == 1) {
                //备注匹配
                if (isset($request['memo']) && ($request['memo'] !== '')) {
                    $response['memo[~]'] = $request['memo'];
                } else {
                    $response['memo[!]'] = '';
                }
            } elseif ($request['is_memo'] == 2) {
                //备注匹配
                if (isset($request['memo']) && ($request['memo'] !== '')) {
                    $response['id'] = 0;
                } else {
                    $response['memo'] = '';
                }
            }
        }

        //备注匹配
        if (isset($request['memo']) && ($request['memo'] !== '')) {
            $response['memo[~]'] = $request['memo'];
        }
        return $response;
    }

    private function jumpScript()
    {
        return <<<SCRIPT
        $('.jump_user').unbind('click').click(function(){
            let win = window.open('http://manage.haohaozhu.me/','用户详情','name=用户详情');
            win.openapp('/User/Oauthadmin/detail/uid/608209','user_detail608209','用户详情');
        });
        
        $('.check').unbind('click').click(function(){
            var id = $(this).data('id');
            var sign = $(this).data('sign');
            if (sign > 0) {
                $.ajax({
                    url:'/admin/activity/designer/' + id,
                    type:"POST",
                    data:{_method:"PUT", name : 'check_status', value : sign},
                    dataType:"json",
                    success:function(result){
                        if (result.status) {
                            toastr.success(result.message);
                        } else {
                            toastr.warning(result.message);
                        }
                    },
                    error:function(){
                        toastr.error('系统错误,请联系管理员');
                    }
                });
            }
        });
SCRIPT;
    }
    public function exportList($rs)
    {
        $list = [];
        if ($rs) {
            foreach ($rs as $v) {
                $list[] = [
                    'id' => $v['id'],
                    'uid' => $v['uid'],
                    'types' => $v['types'],
                    'is_soft' => $v['is_soft'],
                    'areas' => $v['areas'],
                    'areaDesc' => $v['areaDesc'],
                    'house' => $v['house'],
                    'user_nick' => $v['user_nick'],
                    'user_type' => $v['user_type'],
                    'status_desc' => $v['status_desc'],
                    'memo' => $v['memo'],
                    'quality' => $v['quality'],
                    'aid' => $v['aid'],
                    'house_info' => $v['house_info']['h5_url'],
                    'designer_uid' => isset($v['house_info']['house']['designer_uid']) ? $v['house_info']['house']['designer_uid'] : '0',
                ];
            }
        }
        $header = ['id', 'uid', 'types', '软装', 'areas', 'areaDesc', 'house', 'user_nick', 'user_type', 'status_desc', 'memo', 'quality', 'aid', 'house_info', '绑定设计师uid'];
        $letter = range('A', 'O');
        $excelObj = new \Biz\pockets\excel\DownExcel();
        $excelObj->saveType = 0;
        $excelObj->setFileName(date("YmdHis") . '设计师作品列表');
        $excelObj->setSheetTitle('设计师作品列表');

        //设置列宽
        $widths = [
            'A' => 10,
            'B' => 10,
            'C' => 10,
            'D' => 10,
            'E' => 10,
            'F' => 15,
            'G' => 10,
            'H' => 15,
            'I' => 10,
            'J' => 10,
            'K' => 15,
            'L' => 10,
            'M' => 25,
            'N' => 25,
            'O' => 10,
        ];
        //设置货币形式
        $excelObj->setWidth($widths);

        //默认单元格居中
        $excelObj->setDefaultStyleAlignment();
        $excelObj->freezePane('A1');//冻结窗口
        $excelObj->setTextFormat('A');
        $excelObj->setTextFormat('B');
        $excelObj->setTextFormat('F');
        $excelObj->setTextFormat('G');
        $excelObj->setTextFormat('H');
        $excelObj->setTextFormat('I');
        $excelObj->setTextFormat('J');
        $excelObj->setTextFormat('K');
        $excelObj->setTextFormat('L');
        $excelObj->setTextFormat('M');
        $excelObj->setTextFormat('N');
        $excelObj->setTextFormat('O');
        foreach ($header as $key => $value) {
            //设置字体
            $excelObj->setFrontName($letter[$key]);
            //设置加粗
            $excelObj->setFrontBold("$letter[$key]1");
            //设置大小
            $excelObj->setFrontSize($letter[$key]);
        }
        $fileName = $excelObj->create($list, $header);
    }

    private function _index_grid($index_condition, $limit)
    {
        Admin::script($this->jumpScript());

        $list = sAdmDesignerAward::admList($index_condition, $limit);

        if ($_GET['export'] == 1) {
            $this->exportList($list['list']);exit;
        }

        $gridModel = new pGridDataModel($list['list'], $list['total'], [
            'perPage' => $limit[1]
        ]);
        return Admin::grid($gridModel,
            function (Grid $grid) use ($gridModel, $index_condition) {
                $grid->paginate($gridModel->getPerPage());
                $grid->filter(function ($filter) use ($index_condition) {

                    // 去掉默认的id过滤器
                    $filter->disableIdFilter();
                    $filter->column(1 / 2, function ($filter) {
                        //用户身份
                        $filter->equal('role', '用户身份')->select(sAdmDesignerAward::USER_TYPE_MAP);
                        //赛区
                        $filter->equal('area', '赛区')->select(sAdmDesignerAward::USER_AREA);
                        //户型
                        $filter->equal('house', '户型')->select(Sign::USER_HOUSE);
                        //用户id
                        $filter->equal('uid', '用户uid');
                    });
                    $filter->column(1 / 2, function ($filter) {
                        //报名通道
                        $filter->equal('channel', '报名通道')->select(sAdmDesignerAward::ADM_CHANNEL_MAP);
                        //审核状态
                        $filter->equal('check_status', '审核状态')->select(Sign::CHECK_STATUS_MAP);
                        //软装
                        $filter->equal('is_soft', '勾选软装')->radio(['-1' => '全部', '1' => '是', '2' => '否'])->default('-1');
                        //备注
                        $filter->equal('is_memo', '包含备注')->radio(['-1' => '全部', '1' => '是', '2' => '否'])->default('-1');
                        //备注匹配内存
                        $filter->equal('memo', '备注内容');
                    });

                    if (!empty($index_condition)) {
                        $filter->expand();//默认展开
                    }
                });
                $grid->disableExport();
                $grid->disableCreateButton();
                $grid->disableRowSelector();

                $grid->column('id', '报名id');
                $grid->column('user_info', '用户信息')->display(function () {
                    $userInfo[] = 'UID ' . $this->uid;
                    $userInfo[] = '昵称 <a class="jump_user" href="javascript:void(0);"> ' . $this->user_nick . '</a>';
                    $userInfo[] = '身份 ' . $this->user_type;
                    return implode('<br/>', $userInfo);
                });
                $grid->column('areas', '城市');
                $grid->column('areaDesc', '赛区');
                $grid->column('house', '报名户型');
                $grid->column('is_soft', '软装');
                $grid->column('types', '通道');//业主/设计师
                $grid->column('a', '案例')->width(200)->display(function () {
                    $houseInfo = $this->house_info;
                    $link = $houseInfo['h5_url'] ?? "";
                    $a = isset($houseInfo['title']) ? '<a class="fa " href="javascript:layer.open({type: 2, title: \'预览\', maxmin: true, area: [\'800px\', \'500px\'], content: \'' . $link . '\' });">' . htmlentities($houseInfo['title']) . '</a>' : "";
                    $houseSize = isset($houseInfo['house_size']) && ($houseInfo['house_size'] > 0) ? $houseInfo['house_size'] . '平米' : '';
                    $img = "<img width='200' src='{$houseInfo['cover_pic']}'>";
                    return implode('<br/>', [$img, $a, $houseSize,]);
                });
                $grid->column('quality', '案例质量')->display(function () {
                    $qualitySign = '-';
                    if ($this->quality == 5) {
                        $qualitySign = '差';
                    } elseif ($this->quality == 60) {
                        $qualitySign = '普通';
                    } elseif ($this->quality >= 70) {
                        $qualitySign = '优质';
                    }
                    return $qualitySign;
                });
                $grid->column('desc', '作品亮点')->width(200)->display(function () {
                    return '<textarea disabled style="width: 100%;padding: 0.2em;resize: vertical;">' . $this->desc . '</textarea>';
                });
                $grid->column('add_time', '报名时间');
                $grid->column('check_status', '审核状态')->radio(Sign::CHECK_STATUS_MAP);
                $grid->column('memo', '备注')->width(200)->editable();
                $grid->disableActions();
            }
        );
    }

    public function save(Request $request, $id)
    {
        $pjax = true;
        $status = true;
        $name = $request->input('name');
        $value = $request->input('value');
        $check_status = $request->input('check_status');
        $message = "修改成功";
        try {
            if (isset($name) && isset($value)) {
                switch ($name) {
                    case 'memo':
                        $pjax = false;
                        if (mb_strlen($value) > 300) {
                            throw new \Exception('最多300字');
                        }
                        Sign::updateData(['memo' => $value], ['id' => $id]);
                        break;
                    default:
                        throw new \Exception('未开发功能');
                        break;
                }
            } elseif (isset($check_status)) {
                if ($check_status == Sign::CHECK_STATUS_UNDONE) {
                    throw new \Exception('不支持返回未审核');
                }
                Sign::updateData(['check_status' => $check_status], ['id' => $id]);
            } else {
                throw new \Exception('缺少参数错误');
            }
        } catch (\Exception $e) {
            $status = false;
            $message = $e->getMessage();
            if (!$pjax) {
                return response()->json(['errors' => [$message]], 422);
            }
        }
        return response()->json(compact('message', 'status'));
    }


}